package com.tianxiabuyi.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import java.util.List;
import java.util.Map;

/**
 * json转换工具类
 * Created by yang on 2017/3/24.
 */
public final class JSONUtil {
    // 过滤TXBYObject的jsonString属性
    static SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
    static {
        // filter.getExcludes().add("jsonString");
    }

    /**
     * json string转为Map
     */
    public static <T> Map<T, T> mapFromJson(String json) {
        if (json == null)
            return null;
        try {
            return JSON.parseObject(json, new TypeReference<Map<T, T>>(){});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json string转为List
     */
    public static <T> List<T> listFromJson(String json) {
        if (json == null)
            return null;
        try {
            return JSON.parseObject(json, new TypeReference<List<T>>(){});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json string转为类对象
     */
    public static <T> T fromJson(String json, TypeReference<T> t) {
        if (json == null)
            return null;
        try {
            return JSON.parseObject(json, t);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    /**
     * json string转为类对象
     */
    public static <T> T fromJson(String json, Class<T> c) {
        if (json == null)
            return null;
        try {
            return JSON.parseObject(json, c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 类对象转为json string
     */
    public static String toJson(Object obj) {
        if (obj == null)
            return null;
        try {
            return JSON.toJSONString(obj, filter,  SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}